<template>
    <canvas
        class="meshFill_class"
        :width="boxWidth + 'px'"
        :height="boxheight + 'px'"
        id="meshFill-canvas"
    ></canvas>
</template>

<script>
// import axios from 'axios';
import { getHeatMapInf, getHeatMapVal } from 'S/thematicMap';
import { latLngToCoordinate, coordinateToPixel } from 'U/dataQueryFunc';
import common from 'U/common';
export default {
    name: 'meshFill',
    props: {
        beginColor: String,
        endColor: String,
        time: Object,
        geo: String,
        type: String,
    },
    data() {
        return {
            // step: 100,
            boxWidth: '738',
            boxheight: '570',
            xNumL: 0, // 横格子宽度
            yNumL: 0, // 纵格子宽度
            stop: false,
            startTrans: 0,
            endTrans: 0.8,
        };
    },
    methods: {
        setBoxWH({
            borderDis = Number(($('#themetic-canvas').offsetWidth - $('.img_box').offsetWidth) / 2),
            contentName = 'contentId',
        }) {
            this.boxWidth = $(`#${contentName}`).width() - 4 * borderDis;
            this.boxheight = $(`#${contentName}`).height() - 2 * borderDis;
            this.$nextTick(() => {
                this.Canvas = document.getElementById('meshFill-canvas');
                this.ctx = this.Canvas.getContext('2d');
                this.canvasInit();
                this.init();
            });
        },
        canvasInit() {
            this.ctx.strokeStyle = '#000';
            this.ctx.lineWidth = 1;
            // 绘制一个边框
            this.ctx.strokeRect(0, 0, this.Canvas.offsetWidth, this.Canvas.offsetHeight);
        },
        init() {
            this.$store.commit('setIsLoaddingFn', true);
            this.clearCanvas();
            this.querInf();
        },
        // 通过参数查询出数据，并将存放数据的文件名取到
        async querInf() {
            let timeStr =
                this.time.year +
                '-' +
                common.oneToTwo(this.time.month) +
                '-' +
                common.oneToTwo(this.time.date);
            let param = {
                type: this.type,
                startTime: timeStr,
                endTime: timeStr,
                geo: this.geo,
                geoType: 'polygon',
            };
            let res = await getHeatMapInf(param);
            if (res.status === 200) {
                let otherInf = res.data;
                this.dealRespond(otherInf);
                if (otherInf.filenames && otherInf.filenames.length > 0) {
                    this.fileArr = otherInf.filenames;
                    this.fileIndex = 0;
                    this.queryData(0);
                } else {
                    // 当没有返回结果时
                    this.$store.commit('setIsLoaddingFn', false);
                    this.fileIndex = 0;
                    this.$emit('initLegend', this.maxNum, this.minNum);
                }
            }
        },
        // 根据文件名查询对应数据
        async queryData(index) {
            let fileName = this.fileArr[index];
            let res = await getHeatMapVal({ filename: fileName });
            if (res.status === 200) {
                if (index < this.fileArr.length - 1) {
                    index++;
                    this.queryData(index);
                } else {
                    this.$emit('initLegend', this.maxNum, this.minNum);
                    this.$store.commit('setIsLoaddingFn', false);
                }
                this['valArr' + this.fileIndex] = res.data;
                this.setColor();
            }
        },
        // 处理返回结果
        dealRespond(otherInf) {
            let xNum = otherInf.weight; // 横向格子数
            let yNum = otherInf.height; // 纵向格子数
            this.maxNum = otherInf.max;
            this.minNum = otherInf.min;

            let minLng = otherInf.st_xmin; // 横向格子数
            let maxLng = otherInf.st_xmax; // 纵向格子数
            let minLat = otherInf.st_ymin;
            let maxLat = otherInf.st_ymax;
            let latlngArr = latLngToCoordinate([
                [minLng, maxLat],
                [maxLng, minLat],
            ]);
            let poxelArr = coordinateToPixel(latlngArr);
            let minX = poxelArr[0].x;
            let minY = poxelArr[0].y;
            let maxX = poxelArr[1].x;
            let maxY = poxelArr[1].y;
            let boxWidth = maxX - minX;
            let boxheight = maxY - minY;
            let canvasStartX = $('#meshFill-canvas').offset().left;
            let canvasStartY = $('#meshFill-canvas').offset().top;
            this.startPointX = minX - canvasStartX;
            this.startPointY = minY - canvasStartY;

            this.xNumL = boxWidth / xNum;
            this.yNumL = boxheight / yNum;
        },
        // 清空canvas
        clearCanvas() {
            this.ctx &&
                this.ctx.clearRect(1, 1, this.Canvas.offsetWidth - 2, this.Canvas.offsetHeight - 2);
        },
        setColor(oldData) {
            let data = [];
            if (oldData) {
                data = oldData;
            } else {
                data = this['valArr' + this.fileIndex];
                this.fileIndex++;
            }
            for (let i = 0; i < data.length - 1; i++) {
                if (!this.stop) {
                    let pointColor = this.getColorOnePoint(this.minNum, this.maxNum, data[i][0]);
                    let locX = data[i][2];
                    let locy = data[i][1];
                    this.toColor(locX, locy, pointColor);
                }
            }
            if (this.fileIndex === 1) {
                // 渲染完把地图隐藏
                $('.visibilityScreen').css('z-index', '3');
            }
        },
        // 修改颜色值时
        changeColor() {
            this.clearCanvas();
            this.recursiveSetColor(0);
        },
        // 时间改变时
        timeChange() {
            this.clearCanvas();
            if (this.geo) {
                this.init();
            }
        },
        // 修改颜色时递归
        recursiveSetColor(index) {
            if (index < this.fileIndex) {
                this.setColor(this['valArr' + index]);
                index++;
                this.recursiveSetColor(index);
            } else {
                this.$emit('initLegend', this.maxNum, this.minNum);
            }
        },
        // 获取最大最小值
        getMaxAndMin(arr) {
            let min = 0;
            let max = 0;
            for (let i = 0; i < arr.length - 1; i++) {
                if (min > arr[i]) {
                    min = arr[i];
                }
                if (max < arr[i]) {
                    max = arr[i];
                }
            }
            return { minNum: min, maxNum: max };
        },
        // 取点的颜色
        getColorOnePoint(min, max, val) {
            let startRGB = this.beginColor;
            startRGB = startRGB
                .replace('rgb(', '')
                .replace(')', '')
                .split(',');
            let startR = Number(startRGB[0]);
            let startG = Number(startRGB[1]);
            let startB = Number(startRGB[2]);
            let startA = this.startTrans;
            let endRGB = this.endColor;
            endRGB = endRGB
                .replace('rgb(', '')
                .replace(')', '')
                .split(',');
            let endR = Number(endRGB[0]);
            let endG = Number(endRGB[1]);
            let endB = Number(endRGB[2]);
            let endA = this.endTrans;

            let loc = (val - min) / (max - min + 1);
            let resR = loc * (endR - startR) + startR;
            let resG = loc * (endG - startG) + startG;
            let resB = loc * (endB - startB) + startB;
            let resA = loc * (endA - startA) + startA;
            return `rgba(${resR},${resG},${resB},${resA})`;
        },
        // canvas绘制颜色
        toColor(x, y, pointColor) {
            this.ctx.fillStyle = pointColor;
            let startPointX = this.startPointX;
            let startPointY = this.startPointY;
            this.ctx.fillRect(
                startPointX + x * this.xNumL,
                startPointY + y * this.yNumL,
                this.xNumL,
                this.yNumL
            );
            // this.ctx.fillRect(x * this.xNumL, y * this.yNumL, this.xNumL, this.yNumL);
        },
    },
    watch: {
        beginColor(newVal) {
            this.changeColor();
        },
        endColor() {
            this.changeColor();
        },
        time() {
            this.timeChange();
        },
    },
    destroyed() {
        this.stop = true;
    },
};
</script>
<style lang="scss">
.meshFill_class {
    position: absolute;
    z-index: 1;
}
</style>
